var padding_parallel = {
	top: 10,
	rigth: 0,
	bottom: 10,
	left: 24
}; //边框

var div_parallel = d3.select(".map_parallel")
	.append("div")
	.attr("class", "div_parallel");

var others = d3.select(".div_parallel")
	.append("div")
	.attr("id", "other_parallel");

var div3 = document.getElementsByClassName("div_parallel")[0];

//获取div的宽高
var w = div3.offsetWidth - padding_parallel.left - padding_parallel.rigth;
var h = div3.offsetHeight - padding_parallel.top - padding_parallel.bottom - 20;

var width_parallel = w - 25;
var svg_parallel = d3.select(".div_parallel").append("svg")
	.attr("class", "parallel_svg")
	.attr("preserveAspectRatio", "xMidYMid meet")
	.attr("viewBox", "0 0 " + w + " " + h)
	.append("g")
	.attr("transform", "translate(" + padding_parallel.left + "," + padding_parallel.top + ")");

var x = d3.scale.ordinal().rangePoints([0, width_parallel], .5),
	y = {},
	dragging = {};

var line = d3.svg.line(),
	axis = d3.svg.axis().orient("left"),
	background,
	foreground,
	g;

var fisheye = d3.fisheye.scale(d3.scale.identity).domain([0, w]).focus(w / 2).distortion(3);

var psignsItems = getSigns(); //获得球队属性
var pSeason = getSeason(); //获得赛季值
var pTeams = getTeams(); //获得球队名
//球队属性变化
var select_item = select_Item();
select_item.addEventListener("change", function() {
	var index = select_item.selectedIndex;
	var text = select_item.options[index].className.split(".")[0];
	Item_change(text);
}, false);
//赛季变化
var select_season = select_Season();
select_season.addEventListener("change", function() {
	var index = select_season.selectedIndex;
	var text = select_season.options[index].value.split("赛季")[0];
	Season_change(text);
}, false);
//绘制平行坐标图
function DrawParallel(season) {
	d3.csv("data/NBAYearCount.csv", function(error, cities) {
		if (error) throw error;
		// 获得属性维度并生成比例尺
		x.domain(dimensions = d3.keys(cities[0]).filter(function(d) {
			return d != "NO" && d != "Season" && (y[d] = d3.scale.linear()
				.domain(d3.extent(cities, function(p, i) {
					if (p.Season == season) {
						if (d == "Shoot" || d == "Threes" || d == "Penalty") {
							return +p[d].split("%")[0];
						} else return +p[d];
					} else if (d == "Team") {
						return +(i % 30);
					}
				}))
				.range([h, 0]));
		}));
		// 添加背景线
		background = svg_parallel.append("svg:g")
			.attr("class", "background")
			.selectAll("path")
			.data(cities)
			.enter()
			.append("svg:path")
			/*.attr('stroke',function(d){
				for(var i = 0;i<pTeams.length;++i){
					if(pTeams[i].Team == d.Team){
						if(pTeams[i].EASTorWEST == 'East'){
							return '#C6E2FF';
						}
						else{
							return '#FFB6C1';
						}
					}
				}
			})*/
			.attr("d", path_parallel);
		//background.style.opacity = 0.2;

		// 添加前景线
		foreground = svg_parallel.append("svg:g")
			.attr("class", "foreground")
			.selectAll("path")
			.data(cities)
			.enter()
			.append("svg:path")
			.attr("d", path_parallel);
			/*.attr('stroke',function(d){
				for(var i = 0;i<pTeams.length;++i){
					if(pTeams[i].Team == d.Team){
						if(pTeams[i].EASTorWEST == 'East'){
							return '#C6E2FF';
						}
						else{
							return '#FFB6C1';
						}
					}
				}
			})*/
	

		// 添加属性维度
		g = svg_parallel.selectAll(".dimension")
			.data(dimensions)
			.enter()
			.append("svg:g")
			.attr("class", function(d) {
				return d + "-dimension";
			})
			.attr("transform", function(d) {
				return "translate(" + x(d) + ")";
			})
			.call(d3.behavior.drag()
				.on("dragstart", function(d) {
					dragging[d] = this.__origin__ = x(d);
					background.attr("visibility", "hidden");
				})
				.on("drag", function(d) {
					dragging[d] = Math.min(w, Math.max(0, this.__origin__ += d3.event.dx));
					foreground.attr("d", path_parallel);
					dimensions.sort(function(a, b) {
						return position(a) - position(b);
					});
					x.domain(dimensions);
					g.attr("transform", function(d) {
						return "translate(" + position(d) + ")";
					});
				})
				.on("dragend", function(d) {
					delete this.__origin__;
					delete dragging[d];
					transition(d3.select(this)).attr("transform", "translate(" + x(d) + ")");
					transition(foreground)
						.attr("d", path_parallel);
					background
						.attr("d", path_parallel)
						.transition()
						.delay(500)
						.duration(0)
						.attr("visibility", null);
				}));

		// 添加坐标轴
		var i = -1;
		console.log(pTeams);
		g.append("g")
			.attr("class", function(d) {
				return d + "-axis";
			})
			.each(function(d) {
				if (d == "Shoot" || d == "Threes" || d == "Penalty") {
					d3.select(this).call(axis.scale(y[d]).tickSize(2).ticks(10).tickFormat(function(p) {
							return p.toFixed(1) + "%";
						}))
						.selectAll("text")
						.attr("font-size", 11);
				} else if (d == "Team") {
					d3.select(this).call(axis.scale(y[d]).tickSize(2).ticks(28).tickFormat(function(p, j) {
							return pTeams[j].abb;
						}))
						.selectAll("text")
						.attr("font-size", 12)
					/*.style('stroke',function(d,j){
						if(pTeams[j].EASTorWEST == 'East'){
							return '#C6E2FF';
						}
						else{
							return '#FFB6C1';
						}
					})*/
					;
				} else d3.select(this).call(axis.scale(y[d]).tickSize(2).ticks(10).tickFormat(d3.formatPrefix(".1", 1e6)))
					.selectAll("text")
					.attr("font-size", 11);
			})
			.append("text")
			.attr("text-anchor", "middle")
			.attr("font-size", 11)
			.attr("x", -5)
			.attr("y", -8)
			.style('cursor', 'move')
			.text(function(d) {
				for (var i = 0; i < psignsItems.Chinese_name.length; ++i) {
					if (d == psignsItems.English_name[i]) {
						return psignsItems.Chinese_name[i];
					}
				}
			});
		FishEye();
		// 添加滑块
		g.append("g")
			.attr("class", "brush")
			.each(function(d) {
				d3.select(this).call(y[d].brush = d3.svg.brush().y(y[d]).on("brushstart", brushstart).on("brush", brush));
			})
			.selectAll("rect")
			.attr("x", -8)
			.attr("width", 16);
	}); //csv
}

function FishEye() {
	var index = select_season.selectedIndex;
	var season = select_season.options[index].value.split("赛季")[0];
	// 鼠标移动时鱼眼放大
	svg_parallel.on("mousemove", function() {
		fisheye.focus(d3.mouse(this)[0]);

		foreground.attr("d", path_fisheye);
		background.attr("d", path_fisheye);
		g.attr("transform", function(d) {
			return "translate(" + fisheye(x(d)) + ")";
		});
	}); //mouseover
	//
	svg_parallel.on("mouseout", function() {
		var axis_team = d3.select(".Team-axis");
		axis_team.selectAll(".tick")
			.each(function(d) {
				var mytext = d3.select(this).select("text")[0][0];
				mytext.style.opacity = 1;
			});
	}); //mouseout

}
//正常折线绘制
function path_parallel(d) {
	var index = select_season.selectedIndex;
	var season = select_season.options[index].value.split("赛季")[0];
	if (d.Season == season) {
		return line(dimensions.map(function(p) {
			if (p == "Team") {
				for (var i = 0; i < pTeams.length; ++i) {
					if (d[p] == pTeams[i].Team) {
						return [x(p), y[p](pTeams[i].NO)];
					}
				}
			}
			return [x(p), y[p](d[p].split("%")[0])];
		}));
	}
}
//鱼眼放大时折线绘制
function path_fisheye(d) {
	var index = select_season.selectedIndex;
	var season = select_season.options[index].value.split("赛季")[0];
	if (d.Season == season) {
		return line(dimensions.map(function(p) {
			if (p == "Team") {
				for (var i = 0; i < pTeams.length; ++i) {
					if (d[p] == pTeams[i].Team) {
						return [fisheye(x(p)), y[p](pTeams[i].NO)];
					}
				}
			}
			return [fisheye(x(p)), y[p](d[p].split("%")[0])];
		}));
	}
}
//地图点选球队时
function selectTeam(name, season) {
	//将选中球队的所有赛季显示
	var index;
	console.log(season);
	foreground.style("display", function(d) {
		if (d.Team == name) {
			return null;
		} else return "none";
	});
	//确定球队名位置
	var axis_team = d3.select(".Team-axis");
	for (var i = 0; i < pTeams.length; ++i) {
		if (pTeams[i].Team == name) {
			index = pTeams[i].NO;
			break;
		}
	}
	//将其余球队名淡化
	axis_team.selectAll(".tick")
		.each(function(d, i) {
			var mytext = d3.select(this).select("text")[0][0];
			if (index == d) {
				mytext.style.opacity = 1;
			} else {
				mytext.style.opacity = 0.5;
			}
		});

	foreground.style("stroke-width", function(d) {
		if (d.Team == name) {
			return 2;
		} else return 1;
	});
}

//滑块框选范围进行高亮显示
function brush() {
	//actives 是保存当前选中的属性 extents 是保存每个属性框选的最大最小值
	var actives = dimensions.filter(function(p) {
			return !y[p].brush.empty();
		}),
		extents = actives.map(function(p) {
			return y[p].brush.extent();
		});
	foreground.style("display", function(d) {
		return actives.every(function(p, i) {
			if (p == "Shoot" || p == "Threes" || p == "Penalty") {
				return extents[i][0] <= d[p].split("%")[0] && d[p].split("%")[0] <= extents[i][1];
			} else if (p == "Team") {
				for (var j = 0; j < 30; ++j) {
					if (d[p] == pTeams[j].Team) {
						return extents[i][0] <= j && j <= extents[i][1];
					}
				}
			} else {
				return extents[i][0] <= d[p] && d[p] <= extents[i][1];
			}
		}) ? null : "none";
	});
}

function position(d) {
	var v = dragging[d];
	return v == null ? x(d) : v;
}

function transition(g) {
	return g.transition().duration(500);
}

// When brushing, don’t trigger axis dragging.
function brushstart() {
	d3.event.sourceEvent.stopPropagation();
}

//创建球队属性选择框
function select_Item() {
	var select = document.createElement("select");
	select.setAttribute("class", "ItemSelect");
	for (var i = 2; i < psignsItems.Chinese_name.length; ++i) {
		var option = document.createElement("option");
		option.setAttribute("class", psignsItems.English_name[i] + ".option");
		option.text = psignsItems.Chinese_name[i];
		select.appendChild(option);
	}
	var label_Item = document.createElement("label");
	label_Item.setAttribute("class", "label_Item");
	label_Item.innerHTML = "Rank By";
	document.getElementById("other_parallel").appendChild(label_Item);
	document.getElementById("other_parallel").appendChild(select);
	return select;
}
//创建赛季选择框
function select_Season() {
	var select = document.createElement("select");
	select.setAttribute("class", "SeasonSelect");
	for (var i = 0; i < pSeason.length; ++i) {
		var option = document.createElement("option");
		option.setAttribute("class", pSeason[i] + ".option");
		option.text = pSeason[i] + "赛季";
		select.appendChild(option);
	}
	var button = document.createElement("button");
	button.setAttribute("class", "recover");
	button.innerHTML = "Recover";
	button.addEventListener("click", RecoverParallel);
	document.getElementById("other_parallel").appendChild(select);
	document.getElementById("other_parallel").appendChild(button);
	return select;
}

//使平行坐标图恢复原状
function RecoverParallel() {
	var index = select_season.selectedIndex;
	var season = select_season.options[index].value.split("赛季")[0];
	//坐标轴恢复
	g.attr("transform", function(d) {
		return "translate(" + x(d) + ")";
	});
	//背景线恢复
	background
		.attr("d", path_parallel)
		.transition()
		.delay(500)
		.duration(0)
		//.attr("visibility", null);
	//前景线恢复
	foreground
		.attr("d", path_parallel)
		.transition()
		.delay(500)
		.duration(0)
		/*.attr("visibility", null)
		.style("stroke-width", 1)
		.style("display", function(d) {
			return null;
		})*/;

	var axis_team = d3.select(".Team-axis");
	axis_team.selectAll(".tick")
		.each(function(d, i) {
			var mytext = d3.select(this).select("text")[0][0];
			mytext.style.opacity = 1;
		});
}
//球队属性选择
function Item_change(text) {
	var index = select_season.selectedIndex;
	var Season_text = select_season.options[index].value.split("赛季")[0];
	mysort(Season_text, text);
}
//重新定义Y轴
function ReDefineYAxis(season) {
	d3.csv("data/NBAYearCount.csv", function(cities) {
		for (var k = 1; k < dimensions.length; ++k) {
			y[dimensions[k]] = d3.scale.linear()
				.domain(d3.extent(cities, function(p, i) {
					if (p.Season == season) {
						if (dimensions[k] == "Shoot" || dimensions[k] == "Threes" || dimensions[k] == "Penalty") {
							return +p[dimensions[k]].split("%")[0];
						} else return +p[dimensions[k]];
					}
				}))
				.range([h, 0]);
			var axis_item = d3.select("." + dimensions[k] + "-axis");
			axis_item.selectAll(".tick").remove();
			if (dimensions[k] == "Shoot" || dimensions[k] == "Threes" || dimensions[k] == "Penalty") {
				axis_item.append("g")
					.call(axis.scale(y[dimensions[k]])
						.tickSize(2)
						.tickFormat(function(p) {
							return p.toFixed(1) + "%";
						}))
					.selectAll("text")
					.attr("font-size", 11);
			} else {
				axis_item.append("g")
					.call(axis.scale(y[dimensions[k]])
						.tickSize(2)
						.tickFormat(d3.formatPrefix(".1", 1e6))
					)
					.selectAll("text")
					.attr("font-size", 11);
			}
		}
	}); //csv
}

//赛季选择
function Season_change(text) {
	var index = select_item.selectedIndex;
	var item_text = select_item.options[index].className.split(".")[0];
	ReDefineYAxis(text);
	DrawAllRose(text);
	//var one = d3.select('.svg_one').childNodes.length;
	//console.log(one);
	/*if(){
		//Rose_ClickTeam(_TeamName,_Season);
	}
	else{
		
	}*/

	var teamname = document.getElementsByClassName('svg_two')[0].childNodes[0].className.animVal;
	DrawBar(teamname, text);
	mysort(text, item_text);
	Rose_ClickTeam(teamname,text);
	
}
//进行排序
function mysort(season, item) {
	var sortData = [];
	d3.csv("data/NBAYearCount.csv", function(data) {
		var k = 0; //筛选赛季
		for (var i = 0; i < data.length; ++i) {
			if (data[i].Season == season) {
				sortData[k++] = data[i];
			}
		}

		//对所选赛季，球队属性进行排序
		var temp, minIndex;
		for (var i = 0; i < sortData.length - 1; ++i) {
			for (var j = 0; j < sortData.length - i - 1; ++j) {
				if (parseFloat(sortData[j][item]) > parseFloat(sortData[j + 1][item])) {
					temp = sortData[j];
					sortData[j] = sortData[j + 1];
					sortData[j + 1] = temp;
				}
			}
		}
		for (var k = 0; k < sortData.length; k++) {
			if (season == '00-01' || season == '01-02') {
				for (var i = 0; i < pTeams.length; ++i) {
					if (pTeams[i].Team == sortData[k].Team) {
						pTeams[i].NO = k;
						break;
					}
					if (pTeams[i].Team == '新奥尔良鹈鹕') {
						pTeams[i].NO = 29;
					}
				}
			} else {
				for (var i = 0; i < pTeams.length; ++i) {
					if (pTeams[i].Team == sortData[k].Team) {
						pTeams[i].NO = k;
						break;
					}
				}
			}
		}

		//在坐标轴上对球队名按排序顺序进行排列
		var axis_team = d3.select(".Team-axis");
		axis_team.selectAll(".tick")
			.each(function(d, i) {
				var mytext = d3.select(this).select("text");
				for (var j = 0; j < pTeams.length; ++j) {
					if (pTeams[j].NO == i) {
						mytext[0][0].innerHTML = pTeams[j].abb;
						break;
					}
				}
				if ((season == '00-01' || season == '01-02') && i == 29) {
					mytext[0][0].innerHTML = 'NOP';
				}
			}); //each	

		//选中属性的坐标轴移动到与球队名称属性的坐标轴并列
		for (var i = 0; i < dimensions.length; ++i) {
			if (dimensions[i] == item) {
				var temp = dimensions[i];
				dimensions[i] = dimensions[1];
				dimensions[1] = temp;
			}
		}
		x.domain(dimensions);
		g.attr("transform", function(d) {
			return "translate(" + position(d) + ")";
		}); //后续添加动画
		//进行鱼眼放大
		fisheye.focus(x(dimensions[0]));
		g.attr("transform", function(d) {
			return "translate(" + fisheye(x(d)) + ")";
		});

		//对背景线进行重绘
		background
			.attr("d", path_fisheye)
			.transition()
			.delay(500)
			.duration(0)
			.attr("visibility", null);
		//对前景线进行重绘
		foreground
			.attr("d", path_fisheye)
			.transition()
			.delay(500)
			.duration(0)
			.attr("visibility", null);
	}); //d3.csv

}


function selectTeamAndOpponent(name, season) {
	//将选中球队的所有赛季显示
	console.log(season);
	var index1,index2;
	foreground.style("display", function(d) {
		if (d.Team == name[0] || d.Team == name[1]) {
			return null;
		} else return "none";
	});
	//确定球队名位置
	var axis_team = d3.select(".Team-axis");
	for (var i = 0; i < pTeams.length; ++i) {
		if (pTeams[i].Team == name[0]) {
			index1 = pTeams[i].NO;
			break;
		}
	}
	
	for (var i = 0; i < pTeams.length; ++i) {
		if (pTeams[i].Team == name[1]) {
			index2 = pTeams[i].NO;
			break;
		}
	}
	//将其余球队名淡化
	axis_team.selectAll(".tick")
		.each(function(d, i) {
			var mytext = d3.select(this).select("text")[0][0];
			if (index1 == d) {
				mytext.style.opacity = 1;
			}else if (index2 == d) {
				mytext.style.opacity = 1;
			}
			 else {
				mytext.style.opacity = 0.5;
			}
		});

	foreground.style("stroke-width", function(d) {
		if (d.Team == name[0] || d.Team == name[1]) {
			return 2;
		} else return 1;
	});
}
